#pragma once

using namespace System;
using namespace System::Collections::Generic;
using namespace System::Text;
using namespace System::Runtime::InteropServices;

namespace SbCli
{
	public ref class Utf8String
	{
	private:
		IntPtr iPtr;
		int iBufferSize;

	public:
		property IntPtr Pointer
		{
			IntPtr get() { return iPtr; }
		}

		property int BufferLength
		{
			int get() { return iBufferSize; }
		}

		Utf8String(int aBufferSize)
		{
			if (aBufferSize <= 0)
				throw gcnew ArgumentOutOfRangeException("aBufferSize", "Argument must be positive.");

			iPtr = Marshal::AllocHGlobal(aBufferSize);
			iBufferSize = aBufferSize;
		}

		Utf8String(String^ aValue)
		{
			if (aValue == nullptr)
				iPtr = IntPtr::Zero;
			else
			{
				array<Byte>^ bytes = Encoding::UTF8->GetBytes(aValue);
				iPtr = Marshal::AllocHGlobal(bytes->Length + 1);
				Marshal::Copy(bytes, 0, iPtr, bytes->Length);
				Marshal::WriteByte(iPtr, bytes->Length, 0);
				iBufferSize = bytes->Length + 1;
			}
		}

		~Utf8String()
		{
			if (iPtr != IntPtr::Zero)
			{
				Marshal::FreeHGlobal(iPtr);
				iPtr = IntPtr::Zero;
			}
		}
	};
}
